﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Dynamic;

using zijian666.Converts.Abstractions;
using zijian666.Converts.Extensions;

namespace zijian666.Converts.Dynamic;

/// <summary>
/// 动态类型创建工厂
/// </summary>
public static class DynamicFactory
{
    /// <summary>
    /// 构建一个动态类型对象
    /// </summary>
    public static DynamicObject Create(object? value, IConvertSettings convertSettings)
    {
        return value switch
        {
            DBNull or null => DynamicPrimitive.Null,
            DynamicObject dyc => dyc,
            string str => new DynamicPrimitive(str, convertSettings),
            DataRow row => new DynamicDataRow(row, convertSettings),
            DataRowView view => new DynamicDataRow(view.Row, convertSettings),
            NameValueCollection nv => new DynamicNameValueCollection(nv, convertSettings),
            IDataReader reader => new DynamicDictionary(reader.To<IDictionary>()!, convertSettings),
            IDictionary dict => new DynamicDictionary(dict, convertSettings),
            IList list => new DynamicList(list, convertSettings),
            IEnumerator e1 => new DynamicEnumerator(e1, convertSettings),
            IEnumerable e2 => new DynamicEnumerator(e2.GetEnumerator(), convertSettings),
            _ when value.GetType().IsSystemType() => new DynamicPrimitive(value, convertSettings),
            _ => new DynamicEntity(value, convertSettings),
        };
    }
}
